﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataProcessor.EF;
using Hjt212Parser;
using log4net;


namespace DataProcessor.Process
{
    public class ProcessorStatusBiz
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(ProcessorStatusBiz));

        public static void Process()
        {
            try
            {
                var updateFlag = false;
                using (var contextTarget = new PlatformPhContext())
                {
                    var offlines = contextTarget.data_online_latest.Take(1000).ToList();
                    foreach (var offline in offlines)
                    {
                        var master = contextTarget.data_realtime_main.Where(t => t.ps_code.Equals(offline.ps_code)).Where(t => t.pi_code.Equals(offline.pi_code)).OrderByDescending(t => t.monitor_time)
                      .FirstOrDefault();
                        if (master == null || Math.Abs((DateTime.Now - master.monitor_time).TotalHours) > 2)
                        {
                            if (!offline.online_state.Equals("离线"))
                            {
                                offline.online_state = "离线";
                                updateFlag = true;
                            }
                        }
                        else
                        {
                            if (!offline.online_state.Equals("在线"))
                            {
                                offline.online_state = "在线";
                                updateFlag = true;
                            }
                        }
                    }
                    if (updateFlag)
                    { contextTarget.SaveChanges(); }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

    }
}
